package com.sskj.gocoinapp.presenter;

import com.google.gson.Gson;
import com.lzy.okgo.model.Response;
import com.sskj.common.base.HttpData;
import com.sskj.common.http.WebSocketObserver;
import com.sskj.common.util.DisposUtil;
import com.sskj.gocoinapp.http.HttpConfig;
import com.sskj.gocoinapp.ui.fragment.DeepthFragment;
import com.sskj.level.bean.SocketSendBean;
import com.sskj.lib.bean.WSFiveBean;
import com.sskj.lib.http.JsonCallBack;

import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;


public class DeepthFragmentPresenter extends BasePresenter<DeepthFragment> {

    private WebSocketObserver stockSocket;
    private Disposable stockDisposable;

    public void getData(String code) {
        httpService.getDeepData(code)
                .execute(new JsonCallBack<HttpData<List<WSFiveBean>>>() {
                    @Override
                    public void onSuccess(Response<HttpData<List<WSFiveBean>>> response) {
                        HttpData<List<WSFiveBean>> httpData = response.body();
                        if (httpData.getStatus() == HttpConfig.OK) {
                            mView.updateUI(httpData.getData().get(0));
                        }
                    }
                });
    }

    public void initSocket(String code) {
        if (stockSocket == null) {
            stockSocket = httpService.pushCoinFiveDeep(code);
            stockDisposable = stockSocket
                    .map(s -> new Gson().fromJson(s, WSFiveBean.class))
                    .subscribeOn(Schedulers.newThread())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(data -> mView.updateUI(data), e -> {

                    });
        } else {
            stockSocket.send(new Gson().toJson(new SocketSendBean(code)));
        }
    }

    public void sendCode(String code) {

        initSocket(code);
    }

    public void closeWebSocket() {
        stockSocket.close();
        stockSocket = null;

    }

}
